package com.hyc.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hyc.cloud.entities.CommonResult;
import com.hyc.cloud.entities.Payment;
import com.hyc.cloud.service.PaymentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 这里是类说明.
 *
 * @className: CircleBreakerController
 * @author: hyc
 * @date: 2022-02-15 12:14
 */
@RestController
public class CircleBreakerController {

    private static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentService paymentService;

    /**
     * Ribbon负载均衡 blockHandler fallback exceptionsToIgnore 测试方法
     * @title fallback
     * @author hyc
     * @date 2022/2/15 12:15
     * @param id    id
     * @return com.hyc.cloud.entities.CommonResult<com.hyc.cloud.entities.Payment>
     */
    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback"
            // 服务限流自定义方法
            , blockHandler = "blockHandler"
            // 服务降级自定义方法
            , fallback = "handlerFallback"
            // fallback排除的异常
            , exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentInfo/" + id, CommonResult.class, id);

        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        } else if (result== null || result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return result;
    }

    // 服务限流自定义方法
    public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水: blockException  " + blockException.getMessage(), payment);
    }

    // fallback 服务降级方法
    public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "handlerFallback,exception内容  " + e.getMessage(), payment);
    }

    /**
     * OpenFeign测试方法
     * @title paymentSQL
     * @author hyc
     * @date 2022/2/15 14:30
     * @param id    id
     * @return com.hyc.cloud.entities.CommonResult<com.hyc.cloud.entities.Payment>
     */
    @GetMapping(value = "/consumer/openfeign/{id}")
    public CommonResult<Payment> paymentInfo(@PathVariable("id") Long id) {

        return paymentService.paymentInfo(id);
    }

}